<template>
  <div class="colleges-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学院管理</span>
          <el-button
            v-if="userStore.isAdmin"
            type="primary"
            @click="handleCreate"
          >
            新增学院
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="68px">
        <el-form-item label="学院名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入学院名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      
      <!-- 学院表格 -->
      <el-table
        v-loading="loading"
        :data="collegeList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="学院名称" min-width="200" />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin"
              link
              type="warning"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin"
              link
              type="danger"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 学院表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="collegeFormRef"
        :model="collegeForm"
        :rules="collegeFormRules"
        label-width="100px"
      >
        <el-form-item label="学院名称" prop="name">
          <el-input
            v-model="collegeForm.name"
            placeholder="请输入学院名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="学院详情"
      width="500px"
    >
      <el-descriptions :column="1" border v-if="viewCollege">
        <el-descriptions-item label="ID">{{ viewCollege.id }}</el-descriptions-item>
        <el-descriptions-item label="学院名称">{{ viewCollege.name }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(viewCollege.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(viewCollege.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../store/user'
import { getCollegeList, createCollege, updateCollege, deleteCollege, getCollegeById } from '../../api/college'

const userStore = useUserStore()

const loading = ref(false)
const submitLoading = ref(false)
const collegeList = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const currentCollegeId = ref(null)
const viewCollege = ref(null)

const queryForm = reactive({
  name: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const collegeFormRef = ref(null)
const collegeForm = reactive({
  name: ''
})

const collegeFormRules = {
  name: [
    { required: true, message: '请输入学院名称', trigger: 'blur' },
    { min: 2, max: 100, message: '学院名称长度在2到100个字符', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑学院' : '新增学院'
})

// 获取学院列表
const fetchCollegeList = async () => {
  loading.value = true
  try {
    const res = await getCollegeList({
      name: queryForm.name || undefined,
      page: pagination.page,
      size: pagination.size
    })
    
    // res 就是 ApiResponse，res.data 是 PageResult，res.data.data 是列表数据
    collegeList.value = res.data.data || []
    pagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取学院列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchCollegeList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  handleQuery()
}

// 分页改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchCollegeList()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchCollegeList()
}

// 新增
const handleCreate = () => {
  isEdit.value = false
  currentCollegeId.value = null
  resetCollegeForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  currentCollegeId.value = row.id
  Object.assign(collegeForm, {
    name: row.name || ''
  })
  dialogVisible.value = true
}

// 查看
const handleView = async (id) => {
  try {
    const res = await getCollegeById(id)
    // res 就是 ApiResponse，res.data 是实际的学院对象
    viewCollege.value = res.data
    viewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取学院详情失败')
  }
}

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该学院吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCollege(id)
    ElMessage.success('删除成功')
    fetchCollegeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!collegeFormRef.value) return
  
  await collegeFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    
    try {
      if (isEdit.value) {
        await updateCollege(currentCollegeId.value, collegeForm)
        ElMessage.success('更新成功')
      } else {
        await createCollege(collegeForm)
        ElMessage.success('创建成功')
      }
      
      dialogVisible.value = false
      fetchCollegeList()
    } catch (error) {
      // 错误已在拦截器中处理
    } finally {
      submitLoading.value = false
    }
  })
}

// 重置表单
const resetCollegeForm = () => {
  Object.assign(collegeForm, {
    name: ''
  })
  collegeFormRef.value?.clearValidate()
}

// 关闭对话框
const handleDialogClose = () => {
  resetCollegeForm()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchCollegeList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>







